package org.taobao.ibatiside.ui.adapter;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.model.WorkbenchAdapter;
import org.taobao.ibatiside.core.filemodel.FileProber;
import org.taobao.ibatiside.core.filemodel.IbatisConfigFile;
import org.taobao.ibatiside.core.filemodel.IbatisMapperFile;

public class ConfigFileAdapter extends WorkbenchAdapter {
	private final IbatisConfigFile file;

	public ConfigFileAdapter(IbatisConfigFile adaptableObject) {
		file = adaptableObject;
	}

	@Override
	public Object getParent(Object object) {
		return file.getParent();
	}

	@Override
	public String getLabel(Object object) {
		return file.getConfigFile().getProjectRelativePath().toString();
	}

	@Override
	public ImageDescriptor getImageDescriptor(Object object) {
		return org.taobao.ibatiside.ui.Activator
				.getIcon("obj16/ibatisconfig.png");
	}

	@Override
	public Object[] getChildren(Object object) {
		List<IbatisMapperFile> mappers = new ArrayList<IbatisMapperFile>();
		try {
			if (file.getConfigFile().isAccessible()) {
				List<String> resources = FileProber.getMapResources(
						file.getConfigFile(), file.getVersion());
				for (String resource : resources) {
					IbatisMapperFile mf = new IbatisMapperFile(
							findClassPathFile(resource), file);
					mf.setResourceName(resource);
					mappers.add(mf);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mappers.toArray();
	}

	private IFile findClassPathFile(String resource) throws JavaModelException {
		IPackageFragmentRoot[] all = file.getJavaProject()
				.getPackageFragmentRoots();
		for (int i = 0; i < all.length; i++) {
			if (all[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
				IFile file = ((IFolder) all[i].getResource()).getFile(resource);
				if (file.isAccessible()) {
					return file;
				}
			}
		}
		return null;
	}
}
